package com.itheima.aimobile.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.aimobile.domain.Conversation;
import com.itheima.aimobile.mapper.ConversationMapper;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class MySqlChatMemory implements ChatMemory {
    @Autowired
    private ConversationMapper conversationMapper;
    @Override
    public void add(String conversationId, List<Message> messages) {
        List<Conversation> list = messages.stream().map(m -> {
            return Conversation.builder()
                    .type(m.getMessageType().getValue())
                    .message(m.getText())
                    .conversationId(conversationId)
                    .createTime(LocalDateTime.now())
                    .build();
        }).toList();
        conversationMapper.insert(list);
    }

    @Override
    public List<Message> get(String conversationId) {
        //根据会话id进行查询会话记录的内容
        // sql:select * from conversation where conversationId = ?
        List<Conversation> conversations = conversationMapper.selectList(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId, conversationId));
        //把查出来的会话内容转成Message类型，而会话的角色有三种不算system还有两个
       return conversations.stream().map(conversation->{
            Message message = null;
            if(MessageType.ASSISTANT.getValue().equals(conversation.getType())){
                message = new AssistantMessage(conversation.getMessage());
            }else if(MessageType.USER.getValue().equals(conversation.getType())){
                message = new UserMessage(conversation.getMessage());
            }
            return message;
       }).toList();
    }

    @Override
    public void clear(String conversationId) {
        //sql:delete from conversation where conversationId = ?
        conversationMapper.delete(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId,conversationId));
    }
}